package org.jsrml.core.base.service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.jsrml.common.persistence.BaseDao;
import org.jsrml.core.base.command.DeleteRoleCo;
import org.jsrml.core.base.command.SaveResource2RoleCo;
import org.jsrml.core.base.command.SaveRoleCo;
import org.jsrml.core.base.entity.Resource;
import org.jsrml.core.base.entity.Role;
import org.jsrml.core.base.exception.BaException;
import org.jsrml.core.base.qo.ResourceQO;
import org.jsrml.core.base.qo.RoleQO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class RoleService extends BaseDao<Role, RoleQO>{
	
	@Autowired
	private ResourceService resourceService;

	public Role createRole(SaveRoleCo command) {
		Role role = new Role();
		role.create(command);
		save(role);
		return role;
	}
	
	public Role modifyRole(SaveRoleCo command) throws BaException {	
		
		if(StringUtils.isBlank(command.getRoleId())){
			throw new BaException(
					BaException.NECESSARY_PARAM_NULL, "缺少必需的参数!");
		}
		
		RoleQO qo = new RoleQO();
		qo.setId(command.getRoleId());
		qo.setFetchResources(true);
		Role role = queryUnique(qo);
		
		if(role==null){
			throw new BaException(
					BaException.ROLE_NOT_FOUND, "角色没有找到!");
		}
		
		role.modify(command);
		save(role);
		return role;
	}
	
	
	public void resource2Role(SaveResource2RoleCo command) throws BaException{
		if(StringUtils.isBlank(command.getRoleId())){
			throw new BaException(
					BaException.NECESSARY_PARAM_NULL, "缺少必需的参数!");
		}
		
		Role role = get(command.getRoleId());
		
		if(role==null){
			throw new BaException(
					BaException.ROLE_NOT_FOUND, "角色没有找到!");
		}
		
		role.setResources(queryResources(command.getResourceIds()));
		
		save(role);
	}

	private Set<Resource> queryResources(List<String> resourceIds) {
		ResourceQO qo = new ResourceQO();
		qo.setIds(resourceIds);
		List<Resource> resourceList = resourceService.queryList(qo);
		
		Set<Resource> resources = new HashSet<Resource>();
		
		if (resourceList == null) {
			return resources;
		}
		
		for (Resource resource : resourceList) {
			resources.add(resource);
		}
		return resources;
	}

	public void deleteRole(DeleteRoleCo command) {
		delete(command.getRoleId());
	}

	@Override
	protected Criteria buildCriteria(Criteria criteria, RoleQO qo) {
		return criteria;
	}

	@Override
	protected Class<Role> getEntityClass() {
		return Role.class;
	}
}